package com.uoko.common.collection;

import org.springframework.core.CollectionFactory;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Function;
/**
 * <p>
 *
 * </p>
 *
 * @author chenyingchun
 * Email qiaohai@uoko.com
 * created by 2018/6/6 0006
 */
public class MultiList<K, V> implements IMultiList<K, V> {

	public static <K, V> MultiList<K, V> create() {
		return new MultiList<K, V>();
	}

	/**
	 * 
	 */
	private Map<K, List<V>> multiList = Collections.createMap();

	/**
	 * 获取或者创建一个key。
	 * 
	 * @param key
	 * @return
	 */
	private List<V> getOrCreateIndexSet(K key) {

		List<V> set = this.multiList.get(key);
		if (set == null) {
			set = Collections.createList();
			this.multiList.put(key, set);
		}
		return set;

	}

	@Override
	public void put(K key, V value) {

		getOrCreateIndexSet(key).add(value);

	}

	@Override
	public void putAll(K key, Collection<V> values) {

		getOrCreateIndexSet(key).addAll(values);
	}

	@Override
	public void remove(K key, V value) {

		List<V> set = get(key);
		if (set != null) {
			set.remove(value);
		}

	}

	@Override
	public void removeAll(K key) {

		this.multiList.remove(key);

	}

	@Override
	public List<V> get(K key) {

		return this.multiList.get(key);

	}

	@Override
	public void clear() {

		this.multiList.clear();

	}

	@Override
	public boolean isEmpty() {
		return this.multiList.isEmpty();
	}

	@Override
	public boolean containsKey(K key) {

		return this.multiList.containsKey(key);
	}

	@Override
	public boolean containsEntry(K key, V value) {
		List<V> set = get(key);
		return (set != null && set.contains(value));
	}

	@Override
	public Collection<V> replaceValues(K key, Iterable<? extends V> values) {
		/*throw new Exception("该功能未提供！");*/
		return null;
	}

	@Override
	public Set<K> keySet() {

		return this.multiList.keySet();
	}

	@Override
	public Integer count(K key) {
		List<V> tempSet = this.get(key);
		if (tempSet != null)
			return tempSet.size();
		else
			return 0;
	}

	/**
	 * tomap,通用用于对集合建立索引;
	 * 
	 * @param list
	 * @param action
	 * @return
	 */
	public static <K, V> MultiList<K, V> toMap(Collection<V> list, Function<V, K> action) {

		if (list == null || list.isEmpty()) {
			return null;
		}
		MultiList<K, V> resMap = new MultiList<>();
		list.forEach((value) -> {
			resMap.put(action.apply(value), value);
		});
		return resMap;
	}

	@Override
	public Set<Entry<K, List<V>>> entrySet() {
		return this.multiList.entrySet();
	}
	
	
	

}
